<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addData()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr v-if="list.length">
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="delData(item.id)">删除</button>
            <button @click="editData(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          uname: 'Tom',
          age: 19,
          gender: '男',
        },
        {
          id: 2,
          uname: 'Jone',
          age: 21,
          gender: '女',
        },
        {
          id: 3,
          uname: '小李',
          age: 18,
          gender: '男',
        },
      ],
      uname: '',
      age: '',
      gender: '',

      newObj: '',
      flag: false,
    };
  },
  methods: {
    //添加
    addData() {
      if (this.uname && this.age && this.gender) {
        if (!this.flag) {
          const obj = {
            id: this.list.length + 1,
            uname: this.uname,
            age: this.age,
            gender: this.gender,
          };
          this.list = [...this.list, obj];
          this.uname = this.age = this.gender = '';
        } else {
          this.newObj.uname = this.uname;
          this.newObj.age = this.age;
          this.newObj.gender = this.gender;

          this.uname = this.age = this.gender = '';
          this.flag = false;
        }
      } else {
        alert('请输入相应内容');
      }
    },
    //编辑
    editData(id) {
      this.newObj = this.list.find((item) => item.id === id);
      this.uname = this.newObj.uname;
      this.age = this.newObj.age;
      this.gender = this.newObj.gender;
      this.flag = true;
      // this.newObj.flag = true
      // console.log(this.newObj);
    },
    //删除
    delData(id) {
      this.list = this.list.filter((item) => item.id != id);
      this.flag = false;
    },
  },
};
</script>
